<?php
namespace addons\fzdc\library;


use addons\fzdc\library\WxBizDataCrypt;
use think\Config;

class Wxlogin
{
    private $appid;
    private $sessionKey;

    /**
     * 构造函数
     * @param $sessionKey string 用户在小程序登录后获取的会话密钥
     * @param $appid string 小程序的appid
     */
    public function __construct()
    {
        $config = get_addon_config('fzdc');
        $this->sessionKey = $config['secret'];
        $this->appid = $config['appid'];
    }


    /**
     * 微信登录
     * @return array 成功0，失败返回对应的错误码
     */
    public function login($code,$encryptdata,$iv)
    {
        // 根据拿的code来拿access_token
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->sessionKey}&js_code={$code}&grant_type=authorization_code";
        $return = $this->https_request($url);
        $jsonrt = json_decode($return, true);
        if (isset($jsonrt['errcode'])) {
            return ["code"=>0,"msg"=>"微信授权发生错误:{$jsonrt['errmsg']},错误代码：" . $jsonrt['errcode']];
        }
        $sessionKey = $jsonrt['session_key'] ?? '';
        // 根据encryptdata 和 iv 解密获得用户的基本信息
        $pc = new WxBizDataCrypt($this->appid, $sessionKey);
        $errCode = $pc->decryptData($encryptdata, $iv, $data);
        if ($errCode != 0) {
            return ["code"=>0,"msg"=>"数据解析错误，代码：" . $errCode];
        }
        $userInfo = json_decode($data,true);
        $openid = $jsonrt['openid'];
        $mobile = $userInfo['phoneNumber'];
        return ["code"=>1,"data"=>['mobile' => $mobile,  'openid' => $openid]];

    }

    /**
     * 微信登录
     * @return array 成功0，失败返回对应的错误码
     */
    public function get_openid($code)
    {
        // 根据拿的code来拿access_token
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->sessionKey}&js_code={$code}&grant_type=authorization_code";
        $return = $this->https_request($url);
        $jsonrt = json_decode($return, true);
        if (isset($jsonrt['errcode'])) {
            return ["code"=>0,"msg"=>"微信授权发生错误:{$jsonrt['errmsg']},错误代码：" . $jsonrt['errcode']];
        }
        $openid = $jsonrt['openid'];
        return ["code"=>1,"data"=>['openid' => $openid]];

    }


    function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

}

